package org.pwwong.fxscalautils.components.containers

import com.sun.scenario.scenegraph.fx.FXNode

import java.awt.{Dimension,Insets,Rectangle}

import org.pwwong.fxscalautils.Predef._
import org.pwwong.fxscalautils.components.controls.Text
import org.pwwong.fxscalautils.components.layouthints._

import org.pwwong.scalautils.property._
import org.pwwong.scalautils.signals.Predef._

object Stack {
  def apply() = new Stack with AccessibleChildren
} 

class Stack extends Container {    
  protected val _preferredWidth = Prop[Double]( 0.0 )  
  protected val _preferredHeight = Prop[Double]( 0.0 )  
  override lazy val preferredWidth = _preferredWidth  
  override lazy val preferredHeight = _preferredHeight
  
  override protected def layout {
    
    // Set Preferred Width,Height
    _preferredWidth <= children.foldLeft[Double](0.0){ 
      (curMax,child) => if(curMax<child.curWidth()) child.curWidth() else curMax 
    }
    _preferredHeight <= children.foldLeft[Double](0.0){ 
      (curMax,child) => if(curMax<child.curHeight()) child.curHeight() else curMax 
    }
    
    // Set Position
    for( child <- children ){ 
      // Size child
      setWidth(child){
        child.w() match {
          case Preferred() => child.preferredWidth()
          case Fill() => curWidth()
          case PX(pxv) => pxv
          case PCT(pctv) => pctv/100.0*curWidth() 
        }
      }
      setHeight(child){
        child.h() match {
          case Preferred() => child.preferredHeight()
          case Fill() => curHeight()
          case PX(pxv) => pxv
          case PCT(pctv) => pctv/100.0*curHeight()
        }
      }
      // Layout child on x-axis
      setX(child){
        (child.x().origin match {
          case LeftOrigin => 0.0
          case CenterOrigin => curWidth()/2.0
          case RightOrigin => curWidth()
        }) +
        (child.x().offset match {
          case PX(pxv) => pxv.toDouble
          case PCT(pctv) => (curWidth()*(pctv.toDouble/100.0))
        })
      }   
      // Layout child on y-axis
      setY(child)(
        (child.y().origin match {
          case TopOrigin => 0.0
          case MiddleOrigin => curHeight()/2.0
          case BottomOrigin => curHeight()
        }) +
        (child.y().offset match {
          case PX(pxv) => pxv.toDouble
          case PCT(pctv) => (curHeight()*(pctv.toDouble/100.0))
        })
      )
    }
  }
    
}
